#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/time.h> // For struct timeval

#define MYPORT 8888  // Server port
#define BACKLOG 5    // Max pending connections AND max simultaneous clients in this simple example
#define BUF_SIZE 200 // Receive buffer size

int fd_A[BACKLOG]; // Array to store accepted client connection fds
int conn_amount;   // Current number of active connections

// Function to show current client count
void showclient()
{
    printf("--- Active client amount: %d ---\n", conn_amount);
}

int main(void)
{
    int sock_fd, new_fd;            // listen on sock_fd, new connection on new_fd
    struct sockaddr_in server_addr; // server address information
    struct sockaddr_in client_addr; // connector's address information
    socklen_t sin_size;
    int yes = 1;
    char buf[BUF_SIZE];
    int ret; // Generic return value holder
    int i;   // Loop variable

    // Initialize client fd array
    for (i = 0; i < BACKLOG; i++)
    {
        fd_A[i] = 0; // 0 indicates unused slot
    }
    conn_amount = 0; // No clients initially

    // Create listening socket
    if ((sock_fd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
    { // Use AF_INET
        perror("socket");
        exit(1);
    }

    // Set SO_REUSEADDR option
    if (setsockopt(sock_fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1)
    {
        perror("setsockopt");
        close(sock_fd);
        exit(1);
    }

    // Prepare server address structure
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(MYPORT);
    server_addr.sin_addr.s_addr = INADDR_ANY;                         // Bind to any local IP
    memset(server_addr.sin_zero, '\0', sizeof(server_addr.sin_zero)); // Obsolete, but harmless

    // Bind the socket
    if (bind(sock_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1)
    {
        perror("bind");
        close(sock_fd);
        exit(1);
    }

    // Listen for connections
    if (listen(sock_fd, BACKLOG) == -1)
    {
        perror("listen");
        close(sock_fd);
        exit(1);
    }

    printf("Server listening on port %d\n", MYPORT);

    fd_set fdsr;       // The set of file descriptors to monitor for reading
    int maxsock;       // The highest-numbered file descriptor in any of the sets, plus 1
    struct timeval tv; // Timeout for select

    maxsock = sock_fd; // Initially, the listening socket is the highest fd

    while (1)
    {
        // Initialize file descriptor set for select
        FD_ZERO(&fdsr);
        FD_SET(sock_fd, &fdsr); // Add listening socket to monitor for new connections

        // Add active client connections to the set and update maxsock
        for (i = 0; i < BACKLOG; i++)
        {
            if (fd_A[i] != 0)
            {
                FD_SET(fd_A[i], &fdsr);
                if (fd_A[i] > maxsock)
                { // Update maxsock if necessary
                    maxsock = fd_A[i];
                }
            }
        }

        // Set timeout for select (e.g., 30 seconds)
        tv.tv_sec = 30;
        tv.tv_usec = 0;

        // Call select - blocks until activity or timeout
        ret = select(maxsock + 1, &fdsr, NULL, NULL, &tv);

        if (ret < 0)
        { // Error in select
            if (errno == EINTR)
            {
                continue; // Interrupted, restart select
            }
            perror("select error");
            break; // Exit loop on other errors
        }
        else if (ret == 0)
        { // Timeout
            printf("select timeout (30 seconds)\n");
            continue; // Go back to select
        }

        // 1. Check for new connection request on listening socket
        if (FD_ISSET(sock_fd, &fdsr))
        {
            sin_size = sizeof(client_addr);
            new_fd = accept(sock_fd, (struct sockaddr *)&client_addr, &sin_size);

            if (new_fd <= 0)
            {
                if (errno != EINTR)
                {
                    perror("accept error");
                }
            }
            else
            {
                // Find an empty slot in fd_A for the new connection
                int found_slot = -1;
                for (i = 0; i < BACKLOG; ++i)
                {
                    if (fd_A[i] == 0)
                    {
                        fd_A[i] = new_fd;
                        found_slot = i;
                        break;
                    }
                }

                if (found_slot != -1)
                {
                    conn_amount++;
                    printf("New connection client[%d] fd=%d from %s:%d\n",
                           found_slot, new_fd,
                           inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port));
                    if (new_fd > maxsock)
                    {
                        maxsock = new_fd;
                    }
                }
                else
                {
                    printf("Max connections (%d) reached, rejecting %s:%d\n", BACKLOG,
                           inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port));
                    send(new_fd, "Server busy. Try later.\n", 26, 0);
                    close(new_fd);
                }
                showclient();
            }
        }

        // 2. Check existing client connections for incoming data
        for (i = 0; i < BACKLOG; i++)
        {
            if (fd_A[i] != 0 && FD_ISSET(fd_A[i], &fdsr))
            {
                memset(buf, 0, BUF_SIZE);
                ret = recv(fd_A[i], buf, BUF_SIZE - 1, 0);

                if (ret <= 0)
                {
                    if (ret == 0)
                    {
                        printf("Client[%d] fd=%d closed connection.\n", i, fd_A[i]);
                    }
                    else
                    {
                        perror("recv error");
                        printf("Error on client[%d] fd=%d.\n", i, fd_A[i]);
                    }
                    close(fd_A[i]);
                    FD_CLR(fd_A[i], &fdsr); // Should be done before next select, but loop structure handles it implicitly
                    fd_A[i] = 0;
                    conn_amount--;

                    // Recalculate maxsock
                    maxsock = sock_fd;
                    for (int j = 0; j < BACKLOG; ++j)
                    {
                        if (fd_A[j] > maxsock)
                            maxsock = fd_A[j];
                    }
                    showclient();
                }
                else
                {
                    buf[ret] = '\0';
                    printf("Client[%d] fd=%d sent: %s\n", i, fd_A[i], buf);
                }
            }
        }
    }

    printf("Server shutting down.\n");
    close(sock_fd);
    for (i = 0; i < BACKLOG; i++)
    {
        if (fd_A[i] != 0)
        {
            close(fd_A[i]);
        }
    }
    return 0;
}